package com.pine.common.util.async;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;

/**
 * 异步组件
 *
 * @author pine manage
 * @since 2024-08-09
 */
public class AsyncComponent {

    /**
     * 线程池
     */
    private final Executor executor;

    private final List<CompletableFuture<Void>> futures;

    public AsyncComponent(Executor executor) {
        this.executor = executor;
        this.futures = new ArrayList<>();
    }

    /**
     * 增加runnable任务
     *
     * @param runnable runnable
     * @return 当前异步对象
     */
    public AsyncComponent addRunTask(Runnable runnable) {
        futures.add(CompletableFuture.runAsync(runnable, executor));
        return this;
    }

    /**
     * 执行任务
     */
    public void execute() {
        CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();
    }
}
